package org.example.configcenter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.Map;

@Configuration
@EnableConfigurationProperties(ConfigCenterProperties.class)
@ConditionalOnProperty(prefix = "config.center", name = "enabled", havingValue = "true", matchIfMissing = true)
public class ConfigCenterAutoConfiguration implements EnvironmentPostProcessor, Ordered {

    private static final Log logger = LogFactory.getLog(ConfigCenterAutoConfiguration.class);

    private final ConfigCenterProperties properties;

    public ConfigCenterAutoConfiguration(ConfigCenterProperties properties) {
        this.properties = properties;
    }

    @Bean
    @ConditionalOnMissingBean
    public ConfigCenterClient configCenterClient() {
        return new ConfigCenterClient(properties);
    }

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        if (!properties.isEnabled()) {
            logger.info("Config center is disabled");
            return;
        }

        ConfigCenterClient client = configCenterClient();
        Map<String, Object> configs = client.fetchConfigs();

        // 将配置中心的配置添加到环境变量中
        MapPropertySource propertySource = new MapPropertySource("config-center", configs);
        environment.getPropertySources().addFirst(propertySource);

        logger.info("Loaded " + configs.size() + " configurations from config center");
    }

    @Override
    public int getOrder() {
        // 确保在默认的PropertySourceLoader之前执行
        return Ordered.HIGHEST_PRECEDENCE + 10;
    }
}
